package controller

import (
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/labstack/echo"

	"gopkg.in/mgo.v2/bson"

	"m-project-admin/app/entity"
	"m-project-admin/app/manager"
	"m-project-admin/app/model"
	"m-project-admin/app/utils"
)

// 权限校验
func notPermissions(c *echo.Context, loginAdminInfo map[string]interface{}) error {
	isSuper, ok := loginAdminInfo["is_super"]
	if !ok || isSuper != 1 {
		data := make(map[string]interface{})
		data["error_content"] = "😞您没有权限访问😞"
		data["loginAdminInfo"] = loginAdminInfo
		data["env_desc"] = utils.GetEnvDesc()
		return (*c).Render(http.StatusOK, "error.html", data)
	}
	status, ok := loginAdminInfo["status"]
	if !ok || status != 0 {
		data := make(map[string]interface{})
		data["error_content"] = "😞您没有权限访问😞"
		data["loginAdminInfo"] = loginAdminInfo
		data["env_desc"] = utils.GetEnvDesc()
		return (*c).Render(http.StatusOK, "error.html", data)
	}

	return nil
}

// 权限校验
func isNotPermissions(c *echo.Context) bool {
	loginAdminInfo := manager.GetLoginAdminInfo(c)

	isSuper, ok := loginAdminInfo["is_super"]
	if !ok || isSuper != 1 {
		return true
	}
	status, ok := loginAdminInfo["status"]
	if !ok || status != 0 {
		return true
	}

	return false
}

// AddAdmin
func AddAdmin(c echo.Context) error {
	loginAdminInfo := manager.GetLoginAdminInfo(&c)

	// 权限校验
	notPermissions(&c, loginAdminInfo)

	data := make(map[string]interface{})
	data["loginAdminInfo"] = loginAdminInfo
	data["left_item"] = 5
	data["left_item_child"] = 501
	data["env_desc"] = utils.GetEnvDesc()
	return c.Render(http.StatusOK, "add_admin.html", data)
}

// UpdateAdmin
func UpdateAdmin(c echo.Context) error {
	loginAdminInfo := manager.GetLoginAdminInfo(&c)

	// 权限校验
	notPermissions(&c, loginAdminInfo)

	adminId := c.QueryParam("id")
	if adminId == "" {
		// 渲染结果到模板
		data := make(map[string]interface{})
		data["error_content"] = "😞请选择要修改的用户😞"
		data["loginAdminInfo"] = loginAdminInfo
		data["env_desc"] = utils.GetEnvDesc()
		return c.Render(http.StatusOK, "error.html", data)
	}

	// 查询用户信息
	adminUser, _, _ := manager.GetAdminById(adminId)

	// 渲染结果到模板
	data := make(map[string]interface{})
	data["adminUser"] = formatAdmins(adminUser)
	data["loginAdminInfo"] = loginAdminInfo
	data["left_item"] = 5
	data["left_item_child"] = 501
	data["env_desc"] = utils.GetEnvDesc()
	return c.Render(http.StatusOK, "update_admin.html", data)
}

// AdminList
func AdminList(c echo.Context) error {
	loginAdminInfo := manager.GetLoginAdminInfo(&c)

	// 权限校验
	notPermissions(&c, loginAdminInfo)

	skip, page := utils.GetSkipPage(utils.PageCount, c)

	// 查询模板列表
	count, _ := manager.GetAdminCount()
	admins, _ := manager.GetAdminList(skip, utils.PageCount)

	var adminList []map[string]interface{}
	for _, row := range admins {
		item := formatAdmins(row)
		adminList = append(adminList, item)
	}

	res := utils.Paginator(page, utils.PageCount, count)

	// 渲染结果到模板
	data := make(map[string]interface{})
	data["adminList"] = adminList
	data["paginator"] = res
	data["linkPrefix"] = "/adminList?"
	data["total"] = count
	data["loginAdminInfo"] = loginAdminInfo
	data["left_item"] = 5
	data["left_item_child"] = 502
	data["env_desc"] = utils.GetEnvDesc()
	return c.Render(http.StatusOK, "admin_list.html", data)
}

// DoAddAdmin
func DoAddAdmin(c echo.Context) error {
	// 权限校验
	if isNotPermissions(&c) {
		return c.JSON(http.StatusOK, entity.Response{En: 401, Em: "😞您没有权限访问😞"})
	}

	account := c.FormValue("account")
	password := c.FormValue("password")
	name := c.FormValue("name")
	phone := c.FormValue("phone")
	isSuper := c.FormValue("is_super")
	status := c.FormValue("status")

	if account == "" {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "账号不能为空"})
	}
	if password == "" {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "密码不能为空"})
	}
	if name == "" {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "姓名不能为空"})
	}
	if phone == "" {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "手机号不能为空"})
	}

	// 密码长度
	if strings.Count(password, "") < 6 {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "密码长度不能小于6位"})
	}

	// 判断account是否已经存在
	existsAdmin, _, err := manager.GetAdminByAccount(account)
	if err != nil {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: err.Error()})
	}

	if existsAdmin.Id.Hex() != "" {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "该账号已经存在"})
	}

	tmpPwd := utils.Sha1s([]byte(password))
	isSuperTmp, _ := strconv.Atoi(isSuper)
	statusTmp, _ := strconv.Atoi(status)

	admin := model.Admin{
		Id:          bson.NewObjectId(),
		Account:     account,
		Password:    tmpPwd,
		Name:        name,
		Phone:       phone,
		Is_super:    isSuperTmp,
		Status:      statusTmp,
		Create_time: time.Now().Unix(),
		Update_time: time.Now().Unix(),
	}

	_, err = manager.SaveAdmin(admin)
	if err != nil {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "添加失败"})
	}

	return c.JSON(http.StatusOK, entity.Response{En: 200, Em: "成功"})
}

// DoUpdateAdmin
func DoUpdateAdmin(c echo.Context) error {
	// 权限校验
	if isNotPermissions(&c) {
		return c.JSON(http.StatusOK, entity.Response{En: 401, Em: "😞您没有权限访问😞"})
	}

	adminId := c.FormValue("adminid")
	account := c.FormValue("account")
	password := c.FormValue("password")
	name := c.FormValue("name")
	phone := c.FormValue("phone")
	isSuper := c.FormValue("is_super")
	status := c.FormValue("status")

	if adminId == "" {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "请选择要修改的账号"})
	}
	if account == "" {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "账号不能为空"})
	}
	if name == "" {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "姓名不能为空"})
	}
	if phone == "" {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "手机号不能为空"})
	}

	// 密码长度
	if password != "" && strings.Count(password, "") < 6 {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "密码长度不能小于6位"})
	}

	isSuperTmp, _ := strconv.Atoi(isSuper)
	statusTmp, _ := strconv.Atoi(status)

	admin := bson.M{
		"account":     account,
		"name":        name,
		"phone":       phone,
		"is_super":    isSuperTmp,
		"status":      statusTmp,
		"update_time": time.Now().Unix(),
	}

	if password != "" {
		admin["password"] = utils.Sha1s([]byte(password))
	}

	_, err := manager.UpdateAdmin(adminId, admin)
	if err != nil {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: err.Error()})
	}

	return c.JSON(http.StatusOK, entity.Response{En: 200, Em: "成功"})
}

// DoDeleteAdmin
func DoDeleteAdmin(c echo.Context) error {
	// 权限校验
	if isNotPermissions(&c) {
		return c.JSON(http.StatusOK, entity.Response{En: 401, Em: "😞您没有权限访问😞"})
	}

	adminId := c.FormValue("adminid")

	if adminId == "" {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "请选择要删除的账号"})
	}

	// 不能删除自己
	loginAdminInfo := manager.GetLoginAdminInfo(&c)
	tmpAdminId, ok := loginAdminInfo["id"]
	if !ok {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "数据错误"})
	}
	if tmpAdminId == adminId {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "您不能删除自己"})
	}

	// 物理删除账号
	_, err := manager.DeleteAdmin(adminId)
	if err != nil {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: err.Error()})
	}

	return c.JSON(http.StatusOK, entity.Response{En: 200, Em: "成功"})
}

// DoDeleteAdminBatch
func DoDeleteAdminBatch(c echo.Context) error {
	// 权限校验
	if isNotPermissions(&c) {
		return c.JSON(http.StatusOK, entity.Response{En: 401, Em: "😞您没有权限访问😞"})
	}

	ids := c.FormValue("ids")

	if ids == "" {
		return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "请选择要删除的账号"})
	}
	dataidsArray := strings.Split(ids, ",")

	for _, adminId := range dataidsArray {
		// 不能删除自己
		loginAdminInfo := manager.GetLoginAdminInfo(&c)
		tmpAdminId, ok := loginAdminInfo["id"]
		if !ok {
			return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "数据错误"})
		}
		if tmpAdminId == adminId {
			return c.JSON(http.StatusOK, entity.Response{En: 402, Em: "您不能删除自己"})
		}

		// 物理删除账号
		_, err := manager.DeleteAdmin(adminId)
		if err != nil {
			return c.JSON(http.StatusOK, entity.Response{En: 402, Em: err.Error()})
		}
	}
	return c.JSON(http.StatusOK, entity.Response{En: 200, Em: "成功"})
}

func formatAdmins(admin model.Admin) map[string]interface{} {
	item := make(map[string]interface{})
	item["id"] = admin.Id.Hex()
	item["account"] = admin.Account
	item["name"] = admin.Name
	item["phone"] = admin.Phone
	item["status"] = admin.Status
	item["is_super"] = admin.Is_super
	item["create_date"] = time.Unix(admin.Create_time, 0).Format("2006-01-02 15:04:05")
	item["update_date"] = time.Unix(admin.Update_time, 0).Format("2006-01-02 15:04:05")

	return item
}
